package info.niwota.ispy.app;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;

public class AppUtils {
	
	public static List<ResourceInfo> loadAllApplication(Context ctx) {
		ArrayList<ResourceInfo> list = new ArrayList<ResourceInfo>();
		PackageManager pm = ctx.getPackageManager();
		List<ApplicationInfo> apps = pm.getInstalledApplications(0);
		
		Collections.sort(apps, new ApplicationInfo.DisplayNameComparator(pm));
		
		final int cnt = apps.size();
		for (int i = 0; i < cnt; i++) {
			ResourceInfo info = new ResourceInfo();
			ApplicationInfo ai = apps.get(i);
			
			info.title = ai.loadLabel(pm).toString();
			info.packageName = ai.packageName;
			info.name = ai.name;
			info.icon = ai.loadIcon(pm);
			
			list.add(info);
		}

		return list;
	}
	
	public static List<ResourceInfo> loadLauncher(Context ctx) {
		ArrayList<ResourceInfo> list = new ArrayList<ResourceInfo>();
		Intent mi = new Intent(Intent.ACTION_MAIN, null);
		mi.addCategory(Intent.CATEGORY_LAUNCHER);
		
		PackageManager pm = ctx.getPackageManager();
		List<ResolveInfo> apps = pm.queryIntentActivities(mi, 0);
		
		Collections.sort(apps, new ResolveInfo.DisplayNameComparator(pm));

		final int cnt = apps.size();
		for (int i = 0; i < cnt; i++) {
			ResourceInfo info = new ResourceInfo();
			ResolveInfo ri = apps.get(i);
			
			info.title = ri.loadLabel(pm).toString();
			info.packageName = ri.activityInfo.applicationInfo.packageName;
			info.name = ri.activityInfo.name;
			info.icon = ri.activityInfo.loadIcon(pm);
			
			list.add(info);
		}
		
		return list;
	}
}
